public class demo2 {
    //使用升序
    int sum=0;
    int[]temp;
    public int reversePairs(int[] nums) {
        temp=new int[nums.length];//注意提前定义
        gbin(nums,0,nums.length-1);
        return sum;
    }
    public void gbin(int[]nums,int left,int right){
        if(left>=right)return ;
        int mid=(left+right)/2;
        //先将数组左右分组再进行合并
        gbin(nums,left,mid);
        gbin(nums,mid+1,right);
        int cur1=left,cur2=mid+1,x=0;
        while(cur1<=mid&&cur2<=right){
            //  temp[x++]=nums[cur1]<=nums[cur2] ? nums[cur1++] : nums[cur2++];
            if(nums[cur1]<=nums[cur2]){
                temp[x++]=nums[cur1++];
            }else{
                temp[x++]=nums[cur2];
                sum+=mid-cur1+1;
                cur2++;
            }
        }
        while(cur1<=mid)temp[x++]=nums[cur1++];
        while(cur2<=right)temp[x++]=nums[cur2++];
        for(int i=left;i<=right;i++){
            nums[i]=temp[i-left];
        }

    }
    //使用降序，搞清楚逻辑(画图，打草稿)
    int sum1=0;
    int[]temp1;
    public int reversePairs1(int[] nums) {
        temp=new int[nums.length];//注意提前定义
        gbin1(nums,0,nums.length-1);
        return sum;
    }
    public void gbin1(int[]nums,int left,int right){
        if(left>=right)return ;
        int mid=(left+right)/2;
        //先将数组左右分组再进行合并
        gbin(nums,left,mid);
        gbin(nums,mid+1,right);
        int cur1=left,cur2=mid+1,x=0;
        while(cur1<=mid&&cur2<=right){
            //  temp[x++]=nums[cur1]<=nums[cur2] ? nums[cur1++] : nums[cur2++];
            if(nums[cur1]<=nums[cur2]){
                temp1[x++]=nums[cur2++];
            }else{
                temp1[x++]=nums[cur1++];
                sum1+=right-cur2+1;
            }
        }
        while(cur1<=mid)temp1[x++]=nums[cur1++];
        while(cur2<=right)temp1[x++]=nums[cur2++];
        for(int i=left;i<=right;i++){
            nums[i]=temp1[i-left];
        }

    }
}
